/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useEffect, useCallback } from 'react';
import ProCard from '@ant-design/pro-card';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import OrderForm from './_components/OrderForm/index';
import DownloadList from './_components/DownloadList';
import OrderDetail from './_components/OrderDetail';
import type { ActionType } from '@ant-design/pro-table';
import type { QjColumnsListItem, QueryData } from './index.d';
import type { ConnectState } from '@/models/connect';
import type { ProColumns } from '@ant-design/pro-table';
import { cancelOrder, getOrderList } from '@/services/tools/qjOrder';
import { qjColumnsItem, getTableToolbar } from './index.config';
import { initialValues } from './_components/OrderForm/utils';
import { createExportTask, orderCancel, getQueryConfig } from '@/services/tools/qjOrder';
import { debounce } from 'lodash';
import { useSelector } from 'umi';
import styles from './index.less';
import { message, Button, Row, Col } from 'antd';
import CancelModal from './_components/CancelDodal';

const Index = () => {
  const actionRef = useRef<ActionType>();
  const scrollMap = [0, 1575, 2210, 3310];
  const { winSize = '' } = useSelector((state: ConnectState) => state.global);
  const [activity, setActivity] = useState<number>(0);
  const [detail, setDetail] = useState<QjColumnsListItem>({} as QjColumnsListItem);
  const [isOpened, setOpenedDetail] = useState(false);
  const [openCancel, setOpenCancel] = useState(false);
  const [queryData, setQueryData] = useState<QueryData>();
  const [isDownListOpened, setOpenedDownList] = useState(false);
  const [formData, setFormData] = useState(initialValues);
  const handleRequest = async (value: any, param: any) => {
    const { current: page, pageSize } = value;
    const { code, data, msg } = await getOrderList({ page, page_size: pageSize, ...param });
    if (code == 0) {
      return {
        data: data.list,
        total: data.total,
      };
    } else {
      message.error(msg);
      return {};
    }
  };
  const locationTableScrollLeft = (offsetLeft: number) => {
    const box = document.getElementById('qj-order-table');
    const ele = box?.querySelector('.ant-table-content');
    if (ele) {
      ele.scrollLeft = offsetLeft;
    }
  };
  const handleMenuChange = (index: number) => {
    locationTableScrollLeft(scrollMap[index]);
    setActivity(index);
  };
  const getQueryConfigPro = () => {
    getQueryConfig().then((res) => {
      const { data, success } = res;
      if (success) {
        setQueryData(data);
      } else {
        setQueryData({} as QueryData);
      }
    });
  };
  const handleAddDownloadTask = useCallback(
    debounce(() => {
      createExportTask(formData).then(({ success, msg }) => {
        let tip = msg;
        if (success) {
          tip = '添加下载任务成功！快去任务列表查看吧';
        }
        message.success(tip);
      });
    }),
    [formData],
  );
  const onSubmit = (formData_: any) => {
    setFormData(formData_);
    actionRef.current?.reload();
  };

  const handleCancel = (d: { order_id: string; brand: string }) => {
    const { order_id, brand } = d;
    orderCancel({ order_id, brand }).then(({ msg, success }) => {
      let tip = msg;
      if (success) {
        tip = '取消成功';
      }
      message.success(tip);
      actionRef.current?.reload(false);
    });
  };

  const handleShowDetail = (data: object) => {
    setDetail(data as QjColumnsListItem);
    setOpenedDetail(true);
  };

  const handleOperatorClick = (type: string, d: { order_id: string; brand: string }) => {
    switch (type) {
      case 'detail':
        handleShowDetail(d);
        break;
      case 'cancel':
        handleCancel(d);
        break;
    }
  };

  const optionColumns: ProColumns[] = [
    {
      fixed: 'right',
      title: '操作',
      align: 'center',
      width: winSize === 'xs' || winSize === 'sm' ? 50 : 160,
      renderText: (d) => {
        const fit = { xs: 24, md: 12, lg: 12, xl: 12, xxl: 12 };
        const operatorMap = [
          {
            key: 'detail',
            title: '详情',
          },
          // { key: 'edit', title: '编辑' },
          // { key: 'log', title: '日志' },
          {
            key: 'cancel',
            title: '取消订单',
            disabled: d.order_status == 0,
          },
        ];
        return (
          <Row justify='space-between'>
            {operatorMap.map((item) => {
              const { key, title, disabled } = item;
              const clsName = styles[`main__table-operator--${key}`];
              return (
                <Col {...fit} key={key}>
                  <Button
                    size='small'
                    onClick={handleOperatorClick.bind(null, key, d)}
                    className={clsName}
                    key={key}
                    disabled={disabled}
                  >
                    {title}
                  </Button>
                </Col>
              );
            })}
          </Row>
        );
      },
    },
  ];

  useEffect(() => {
    const box = document.getElementById('qj-order-table');
    const ele = box?.querySelector('.ant-table-content');
    getQueryConfigPro();
    ele?.addEventListener('scroll', (res) => {
      // res.scrollLeft
      const scrollLeft = res.target?.['scrollLeft'];
      const index = scrollMap.findIndex((value, i) => {
        return scrollLeft > value && scrollLeft < (scrollMap[i + 1] || 99999);
      });
      if (index !== -1) {
        setActivity(index);
      }
    });
  }, []);

  const handleCancelOrder = (value = {}) => {
    cancelOrder({
      ...value,
      order_id: detail.order_id,
    }).then((res) => {
      if (res.code == 0) {
        setOpenCancel(false);
        setOpenedDetail(false);
        actionRef.current?.reload(false);
        message.success(res.msg);
      } else {
        message.error(res.msg);
      }
    });
  };
  return (
    <ProCard>
      <DragTable className={styles.main}>
        <OrderForm onSubmit={onSubmit} />
        <OrderDetail
          data={detail}
          isOpened={isOpened}
          onCancel={() => setOpenedDetail(false)}
          onOk={() => setOpenedDetail(false)}
          queryData={queryData}
          onRefund={() => {
            setOpenCancel(true);
          }}
        />
        <CancelModal
          open={openCancel}
          onOk={handleCancelOrder}
          onCancel={() => {
            setOpenCancel(false);
          }}
        />
        <ProTable<QjColumnsListItem>
          id='qj-order-table'
          actionRef={actionRef}
          rowKey='order_id'
          request={(values) => handleRequest(values, formData)}
          toolbar={getTableToolbar({
            winSize,
            activity: activity,
            handleMenuChange,
            isDownListOpened,
            setOpenedDownList,
            handleAddDownloadTask,
          })}
          columns={[...qjColumnsItem(queryData), ...optionColumns]}
          pagination={{
            pageSize: 30,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          scroll={{ x: 5700 }}
          options={false}
          search={false}
        />
        <DownloadList isOpened={isDownListOpened} onCancel={() => setOpenedDownList(false)} />
      </DragTable>
    </ProCard>
  );
};

export default Index;
